let ws = new WebSocket('ws:localhost:8000')
let btn = document.getElementById('btn')
let body = document.querySelector('body')
let div = document.querySelector('div')
//监听连接事件
ws.addEventListener('open', function () {
  console.log('客户端建立连接啦');
})
//监听服务器发送消息
ws.addEventListener('message', function (e) {
  let { user, date, message } = JSON.parse(e.data)
  let html = `
      <ul>
        <li>${user}</li>
        <li>${date}</li>
        <li style='color:red'>${message}</li>
      </ul>
      `
  div.innerHTML += html
  console.log('服务端发消息来啦', e.data);
})
ws.addEventListener('close', function () {
  console.log('连接关闭啦');
})
let msg = {
  user: '李坤',
  date: Date.now(),
  message: '你好在吗？'
}
btn.addEventListener('click', function () {
  ws.send(JSON.stringify(msg))
})